package cn.blogs.show.everythin.work.queues.consumer;

import com.rabbitmq.client.*;
import utils.RabbitMqUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class WorQueuesConsumerThree {
    // 消费段限流
    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            // 获取连接
            connection = RabbitMqUtils.getConnection();
            if (connection != null) {
                // 创建通道
                channel = connection.createChannel();
                channel.queueDeclare("work_queues_test", true, false, false, null);

                // 每次只发发送一条消息给同一消费者
                channel.basicQos(1);
                Channel finalChannel = channel;
                channel.basicConsume("work_queues_test", false, new DefaultConsumer(finalChannel) {

                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                        try {
                            TimeUnit.SECONDS.sleep(2);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("envelope:" + envelope.getDeliveryTag());
                        System.out.println("Consumer-three:" + new String(body));
                        finalChannel.basicAck(envelope.getDeliveryTag(), false);
                    }
                });


            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
